<template>
  <div id="member_balance_detailed_v2">
    <c-title :hide="false" :text="balanceLang + '明细'"></c-title>
    <div class="background_box"></div>
    <div class="statusBox">
      <div class="statusBox_left">
        <div class="txt" :class="statusValue == 0 ? 'showtxt' : ''" @click="selectStatus(0)">全部</div>
        <div class="txt" :class="statusValue == 1 ? 'showtxt' : ''" @click="selectStatus(1)">收入</div>
        <div class="txt" :class="statusValue == 2 ? 'showtxt' : ''" @click="selectStatus(2)">支出</div>
      </div>
      <div class="statusBox_right" @click.stop="selectShow = !selectShow" v-if="serviceTypeList.length > 0">
        <div class="txt">{{ serviceTypeList[selectTapInd].name }}</div>
      </div>
    </div>
    <template v-if="!noneShow">
      <template v-for="(item, index) in record_list.data">
        <div class="timeSelect" :key="index">
          <div class="timeBox" @click="show = true">
            <div class="time">{{ index }}</div>
            <van-icon name="arrow-down" size="12px" />
          </div>
          <div class="totalNum">支出：￥{{ money_arr[index] ? money_arr[index].expend : "0.00" }} 收入：￥{{ money_arr[index] ? money_arr[index].income : "" }}</div>
        </div>
        <div class="list" :key="index">
          <div class="lis" v-for="(info, index) in item" :key="index" @click="detailsTo(info)">
            <div class="lisTop">
              <div class="txtName">{{ info.service_type_name }}</div>
              <div class="price">{{ info.type == 1 ? "+" : "" }}{{ info.change_money }}</div>
            </div>
            <div class="lisTop dob">
              <div class="time">{{ info.created_at }}</div>
              <div class="balance">{{ balanceLang }}：{{ info.new_money }}</div>
            </div>
          </div>
        </div>
      </template>
    </template>
    <template v-else>
      <div class="timeSelect" :key="index">
        <div class="timeBox" @click="show = true">
          <div class="time">{{ choose_time }}</div>
          <van-icon name="arrow-down" size="12px" />
        </div>
        <div class="totalNum">支出：￥0.00 收入：￥0.00</div>
      </div>
      <div class="list">
        <div class="listTxt">暂无记录</div>
      </div>
    </template>

    <van-popup v-model="show" position="bottom" :style="{ height: '40%' }">
      <van-datetime-picker @confirm="pickConfirm" @cancel="show = false;" v-model="currentDate" type="year-month" title="选择年月" :max-date="maxDate" :formatter="formatter" />
    </van-popup>
    <van-popup v-model="selectShow" position="bottom" :style="{ height: '40%' }">
      <div class="typeBox">
        <div class="lis" :class="item.id == selectType ? 'lisBg' : ''" v-for="(item, index) in serviceTypeList" :key="item.id" @click="selectTap(item.id, index)">
          <div class="txt">{{ item.name }}</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { scrollMixin } from "utils/mixin";
export default {
  mixins: [scrollMixin],
  data() {
    return {
      //余额字样
      balanceLang: this.fun.getBalanceLang(),
      statusValue: 0,
      // 筛选类型 弹窗
      selectShow: false,
      selectType: 0,
      record_list: [],
      money_arr: [],
      currentDate: new Date(),
      maxDate: new Date(),
      show: false,
      choose_time:"",
      postDate: "",
      noneShow: false,
      selectTimeDate: "",
      // 筛选类型数组
      serviceTypeList: [],
      selectTapInd: 0,

      isLoadMore: true,
      page: 1,
      total_page: 0
    };
  },
  methods: {
    detailsTo(info) {
      this.$router.push(this.fun.getUrl("details", { item: info }));
    },
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      }
      return val;
    },
    selectStatus(key) {
      if(this.noneShow){
        return
      }
      this.init();
      this.statusValue = key;
      this.getData();
    },
    selectTap(key, ind) {
      this.init();
      this.selectType = key;
      this.selectTapInd = ind;
      // this.selectTap = false;
      this.getData();
    },
    pickConfirm(e) {
      this.postDate = this.timestampToTime(Date.parse(e));
      this.choose_time =  this.timestampToTime(Date.parse(e),'yyyy-mm');
      this.show = false;
      this.init();
      this.getData();
    },
    init() {

      this.isLoadMore = true;
      this.page = 1;
      this.total_page = 0;
      this.record_list = [];
      this.money_arr = [];
      this.selectShow = false;
    },
    //将时间戳转换成正常时间格式
    timestampToTime: function(timestamp, key) {
      if (!Number(timestamp) || timestamp == "") {
        return "";
      }
      let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + "-";
      let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1);
      let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      if(key=='yyyy-mm'){
        return Y + M
      }
      return Y + M +  "-"+D;
    },
    serviceType() {
      $http
        .post("finance.balance.get-service-type-list", {}, "加载中")
        .then(response => {
          if (response.result === 1) {
            this.serviceTypeList = response.data;
            let arr = { id: 0, name: "业务类型" };
            this.serviceTypeList.unshift(arr);
            console.log(this.serviceTypeList);
          } else {
            this.noneShow = true;
            this.isLoadMore = false; // 防止多次请求分页数据
            this.record_list = [];
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getData() {
      let json = {
        search: {
          record_type: this.statusValue,
          date: this.postDate,
          service_type: this.selectType
        }
      };
      let urlstr = "finance.balance.record";
      if(this.$route.name == 'wechat_sidebarDetailed'){
        urlstr = "plugin.wechat-chat-sidebar.frontend.controller.finance.balance.record";
      }
      $http
        .post(urlstr, json, "加载中")
        .then(response => {
          if (response.result === 1) {
            this.isLoadMore = true;
            this.noneShow = false;
            this.total_page = response.data.record_list.last_page;
            if (!this.total_page) {
              this.total_page = 0;
            }
            this.money_arr = response.data.money_arr;
            this.record_list = response.data.record_list;
          } else {
            this.noneShow = true;
            this.isLoadMore = false; // 防止多次请求分页数据
            this.record_list = [];
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getMoreData() {
      if (!this.isLoadMore) return;
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.total_page) {
        return;
      } else {
        this.page += 1;
        let json = {
          search: {
            record_type: this.statusValue,
            date: this.postDate,
            service_type: this.selectType
          },
          page: this.page
        };
        $http.post("finance.balance.record", json).then(response => {
          if (response.result === 1) {
            var nextPageData = response.data.record_list.data;
            this.money_arr = Object.assign(this.money_arr, response.data.money_arr);
            for (const key in nextPageData) {
              if (this.record_list.data[key]) {
                this.$set(this.record_list.data, key, [...this.record_list.data[key], ...nextPageData[key]]);
              } else {
                this.$set(this.record_list.data, key, nextPageData[key]);
              }
            }
            this.isLoadMore = true;
            console.log(this.record_list.data);
          } else {
            this.page = this.page - 1;
            this.isLoadMore = false;
          }
        });
      }
    },
    getStartOfMonth() {
      const now = new Date();
      return new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0);
    },
  },
  activated() {
    const startOfMonth = this.getStartOfMonth();
    this.currentDate= new Date();
    this.postDate = this.timestampToTime(startOfMonth);
    this.choose_time =  this.timestampToTime(Date.now(),'yyyy-mm');
    this.getData();
    if(this.$route.name != 'wechat_sidebarDetailed'){
      this.serviceType();
    }
  }
};
</script>
<style lang="scss" scoped>
.listTxt {
  padding: 2rem 0;
}

@keyframes ident {
  0% {
    opacity: 0;
  }

  50% {
    opacity: 0.75;
  }

  100% {
    opacity: 1;
  }
}

.showPosBox {
  animation: ident 0.5s;
}

.background_box {
  color: #382c0a;
  background-color: #fff;
  background-image: -webkit-gradient(linear, left top, left bottom, from(var(--themeBaseColor)), to(#f5f5f5));
  background-image: -webkit-linear-gradient(var(--themeBaseColor), #f5f5f5);
  background-image: linear-gradient(var(--themeBaseColor), #f5f5f5);
  min-height: 9.25rem;
  padding: 1.5938rem 1.0938rem 0 1.0938rem;
}

.statusBox {
  margin: 0 0.625rem;
  margin-top: -7rem;
  margin-bottom: 0.625rem;
  display: flex;
  justify-content: space-between;
  z-index: 1;
  position: relative;

  .statusBox_left {
    display: flex;
    font-size: 0.75rem;
    color: #262626;

    .txt {
      line-height: 1.875rem;
      width: 3.75rem;
    }

    .showtxt {
      width: 3.75rem;
      height: 1.875rem;
      background: #fff;
      border-radius: 0.9375rem;
    }
  }

  .statusBox_right {
    min-width: 5.3125rem;
    height: 1.875rem;
    background: #fdefbd;
    border-radius: 0.3125rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 0.4688rem;
    position: relative;

    .txt {
      flex: 1;
      text-align: center;
    }

    .statusBox_right_pos {
      background: #fdefbd;
      position: absolute;
      bottom: -4.3rem;
      left: 0;
      width: 100%;
      z-index: 22222222;
      border-radius: 0 0 0.3125rem 0.3125rem;

      .postxt {
        height: 1.5rem;
        line-height: 1.5rem;
      }
    }
  }
}

.list {
  margin: 0 0.625rem;
  padding: 0 0.875rem;
  margin-top: 0.9375rem;
  background: #fff;
  border-radius: 0.625rem;
  margin-bottom: 0.625rem;

  .lis:first-child {
    border: none;
  }

  .lis {
    display: flex;
    flex-direction: column;
    padding: 0.9375rem 0;
    border-bottom: 1px solid #f6f6f6;

    .dob {
      margin-top: 0.4688rem;
    }

    .lisTop {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .txtName {
        font-size: 14px;
      }

      .price {
        font-size: 14px;
        font-weight: 500;
        color: #f20606;
      }

      .time {
        font-size: 0.6875rem;
        color: #999;
      }

      .balance {
        font-size: 0.6875rem;
        font-weight: 400;
        color: #666;
      }
    }
  }
}

.timeSelect {
  margin-top: -5rem;
}

.timeSelect {
  height: 2.5rem;
  background: #fff;
  border-radius: 0.625rem;
  margin: 0 0.625rem;
  display: flex;
  padding: 0 0.9063rem;
  align-items: center;
  position: sticky;
  top: 40px;

  .timeBox {
    flex-shrink: 0;
    display: flex;
    align-items: center;

    .time {
      margin-right: 0.5rem;
      font-size: 0.8125rem;
    }
  }

  .totalNum {
    flex: 1;
    text-align: right;
    font-size: 14px;
    color: #333;
  }
}

.typeBox {
  overflow-y: scroll;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  padding: 0.625rem;
  padding-top: 1rem;

  .lis {
    width: 30%;
    padding: 0.6rem 0.625rem;
    border-radius: 0.1563rem;
    background: #9999;
    margin-right: 1rem;
    margin-bottom: 0.625rem;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;

    .txt {
      font-size: 12px;
    }
  }

  .lis:nth-child(3n) {
    margin-right: 0;
  }

  .lisBg {
    background: var(--themeBaseColor) !important;
  }
}
</style>
